import 'package:yp/config/config.dart';
import 'package:get/get.dart';
import 'package:yp/pages/main/logic.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:sp_util/sp_util.dart';
import '../../helper.dart';
import 'state.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class OrderCreateLogic extends GetxController {
  final state = OrderCreateState();

  // final MainAppLogic MainAppLogics = Get.put(MainAppLogic());
  final MainLogic mainLogic = Get.put(MainLogic());

  @override
  void onInit() {
    print('购物车初始化1');
    super.onInit();
    if (Get.arguments != null) {
      if (Get.arguments["type"] == '1') {
        var params = {
          "mobile": Get.arguments["phone"],
          "usr_num_id": null,
          "usr_type": 1
        };
        Api.searchMember(params).listen((event) {
          if (event["code"] == 0) {
            state.orderMemberData = event;
            SpUtil.putString('userNumId', event["usr_num_id"].toString());
            update();
          } else {
            Get.toNamed(RouteConfig.searchMember,
                arguments: {"phone": Get.arguments["phone"]}).then((value) {
              if (value != '' && value != null) {
                state.orderMemberData = value;
                SpUtil.putString('userNumId',
                    state.orderMemberData["usr_num_id"].toString());
                onReady();
                update();
              }
            });
          }
        });
        return;
      }
    }

    // 测试用
    else if (SpUtil.getString('userNumId') != '' &&
        SpUtil.getString('userNumId') != null) {
      var params = {
        "mobile": null,
        "usr_num_id": SpUtil.getString('userNumId'),
      };
      Api.searchMember(params).listen((event) {
        print(params);
        state.orderMemberData = event;
        update();
      });
    }
  }

  @override
  void onReady() {
    super.onReady();
    print('1111111111111111111111');
    state.edit = false;
    if (SpUtil.getInt('empeNumId') != '') {
      cartGoodsData();
      getrecommendGoods();
    }
  }

  void setSex(int sex) {
    state.sendType = sex;
    update();
  }

  void selectStatus(int index) {
    if (index == 2) {
      Get.toNamed(RouteConfig.orderDeposit);
    }
    state.statusIndex = index;
    update();
  }

  //购物车商品数据
  void cartGoodsData() {
    getCurrentLocationInfo(success: (data) {
      state.orderAddress = data['addressInfo'];
      var params = {
        "usr_num_id": SpUtil.getInt('empeNumId'),
        "use_platform": 2,
        "prv_num_id": state.orderAddress['prv_num_id'],
        "city_num_id": state.orderAddress['city_num_id'],
        "city_area_num_id": state.orderAddress['city_area_num_id'],
        "town_num_id": state.orderAddress['town_num_id'],
        "maplocation_x": state.orderAddress['maplocation_x'],
        "maplocation_y": state.orderAddress['maplocation_y'],
        "adr_num_id": state.orderAddress["adr_num_id"],

        // "usr_num_id": SpUtil.getInt('empeNumId'),
        'access_token': SpUtil.getString('token'),
      };
      print(' print(params); print(params); print(params);');
      print(params);
      Api.cartGoodsData(params).listen((event) {
        print('event["multi_shop_items"]');
        print(event["multi_shop_items"]);
        if (event["multi_shop_items"] == null) {
          state.cartDataList = [];
        } else {
          state.cartDataList = event["multi_shop_items"];
        }
        state.cartData = event;

        print('state.cartData');
        print(state.cartData);
        getclickNum();
        mainLogic.getCartNum();
        getshopTag();
        getSxGoodList(event["multi_shop_items"][0]);

        update();
      });
    });
  }

  //清除失效商品
  clearsxArr() {
    List cart_idarr = [];
    state.sxGoodList.forEach((element) {
      cart_idarr.add(element['cart_id']);
    });
    var params = {
      'access_token': SpUtil.getString('token'),
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      "cart_id": getTaskScreen(cart_idarr) //多个用逗号隔开
    };
    print(params);

    Api.cartDelete(params).listen((event) {
      if (event["code"] == 0) {
        state.sxGoodList.clear();
        update();
      }
    });
  }

  ///获取失效商品
  getSxGoodList(data) {
    state.sxGoodList = [];
    // if(data['stock_out_list'].length)
    if (data['stock_out_list'].length > 0 && data['stock_out_list'] != null) {
      data['stock_out_list'].forEach((element) {
        state.sxGoodList.add(element);
      });
    }
    if (data['sold_out_list'].length > 0 && data['sold_out_list'] != null) {
      data['sold_out_list'].forEach((element) {
        state.sxGoodList.add(element);
      });
    }
    if (data['without_list'].length > 0 && data['without_list'] != null) {
      data['without_list'].forEach((element) {
        state.sxGoodList.add(element);
      });
    }
    if (data['delivery_out_list'].length > 0 &&
        data['delivery_out_list'] != null) {
      data['delivery_out_list'].forEach((element) {
        state.sxGoodList.add(element);
      });
    }
    if (data['shop_close_list'].length > 0 && data['shop_close_list'] != null) {
      data['shop_close_list'].forEach((element) {
        state.sxGoodList.add(state.sxGoodList);
      });
    }
    print('失效商品');
    print(state.sxGoodList);
    update();
  }

  getrecommendGoodsList() {
    getCurrentLocationInfo(success: (data) {
      state.orderAddress = data['addressInfo'];
      var params = {
        "use_platform": 2,
        "is_recommend": 1,
        // "shop_id": shopId,

        "prv_num_id": state.orderAddress['prv_num_id'],
        "city_num_id": state.orderAddress['city_num_id'],
        "city_area_num_id": state.orderAddress['city_area_num_id'],
        "town_num_id": state.orderAddress['town_num_id'],
        "maplocation_x": state.orderAddress['maplocation_x'],
        "maplocation_y": state.orderAddress['maplocation_y'],
        "adr_num_id": state.orderAddress["adr_num_id"],

        "page_no": 1,
        "page_size": 10,
        "access_token": SpUtil.getString('token')
      };
      Api.recommendGoods(params).listen((event) {
        if (event["code"] == 0) {
          // state.recommendGoods = event;
          update();
        }
      });
    });
  }

  ///获取购物车角标
  getshopTag() {
    var params = {
      "from_where": 1,
      // "shop_id": SpUtil.getInt('storeShopNum'),
      "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      "super_ec_shop_num_id": 100049001,
      "use_platform": "2"
    };
    Api.shopTag(params).listen((event) {
      if (event["code"] == 0) {
        event['cart_norm_tag'].forEach((f) {
          if (f['tag_type'] == 'promotion_cat') {
            state.promotion_cat = f;
          }
          if (f['tag_type'] == 'activity_cat') {
            state.activity_cat = f;
          }
        });

        List arr = state.promotion_cat['fillet'].split(",");
        List arr2 = state.promotion_cat['fillet'].split(",");
        for (var i = 0; i < arr.length; i++) {
          state.angle[i] = double.parse(arr[i]);
        }
        for (var j = 0; j < arr.length; j++) {
          state.cxangle[j] = double.parse(arr2[j]);
        }
        print('111111111111111111111111111111111111111111111111111111111');
        print(state.angle);
        update();
      }
    });
  }

  ///获取商品规格
  void goodsSpecifications(data) {
    var params = {
      "shop_id": data["ec_shop_num_id"],
      "style_num_id": data["style_num_id"],
      "ec_style_num_id": data["ec_style_num_id"],
      "default_item_num_id": data["item_num_id"],
    };
    //获取选择商品规格数据
    Api.goodsSpecifications(params).listen((event) {
      state.goodsSpecificationsData = event["spec"];
      //默认选中项
      var idNum = event["spec"]["default_prop_id"].toString();
      // //默认选中商品图片
      state.goodsSpecificationsImageData =
          event["spec"]["spec_item"][idNum]["image_default_id"];
      // //默认选中商品规格标题
      state.goodsSpecificationsTitleData =
          event["spec"]["spec_item"][idNum]["item_name"];
      //商品规格列表
      // List data = event["spec"]["specs"]["specs"];
      //商品规格列表数据
      state.selectSpecifications = event["spec"]["default_prop_id"].toString();
      // data.forEach((element) {
      //   state.selectSpecifications.add(element['spec_values'][0]['spec_value_id']);
      // });
      // String selectSpecifications = state.selectSpecifications.join('_').toString();
      state.sumParic =
          event["spec"]["spec_item"][state.selectSpecifications]["price"];

      update();
    });
  }

  //删除商品
  void cartDelete(params) {
    Api.cartDelete(params).listen((event) {
      if (event["code"] == 0) {
        cartGoodsData();

        update();
      }
    });
  }

  //选中商品加入购物车
  void addShoppingCart(params) {
    Api.addShoppingCart(params).listen((event) {
      //添加成功获取购物车商品数量
      if (event["code"] == 0) {
        toast("添加成功");
        cartGoodsData();
        Get.back(result: true);
      } else {
        toast(event['message']);
      }
    });
  }

  //购物车商品全选

  void cartChoose(params) {
    Api.cartChoose(params).listen((event) {
      //添加成功获取购物车商品数量
      cartGoodsData();
    });
  }

  //购物车编辑修改数量
  void cartItemEdit(id, checked, sum) {
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "use_platform": 2,
      // "emp_num_id": SpUtil.getInt('empeNumId'),
      "cart_params": [
        {"cart_id": id, "is_checked": checked, "total_quantity": sum}
      ],
      'access_token': SpUtil.getString('token'),
    };
    print(params);
    Api.cartItemEdit(params).listen((event) {
      if (event["code"] == 0) {
        cartGoodsData();
        update();
      }
    });
  }

  //获取自提点列表数据
  void selfHelpAddress() {
    var params = {
      "prv_num_id": state.orderAddress['prv_num_id'],
      "city_num_id": state.orderAddress['city_num_id'],
      "city_area_num_id": state.orderAddress['city_area_num_id'],
      "town_num_id": state.orderAddress['town_num_id'],
      "maplocation_x": state.orderAddress['maplocation_x'],
      "maplocation_y": state.orderAddress['maplocation_y'],
      "adr_num_id": state.orderAddress["adr_num_id"],

      "page": 1,
      "page_size": 10,
      'user_type': 1, //用户类型:1网格员,2KOC
      'usr_num_id': SpUtil.getInt('empeNumId')
    };
    Api.selfHelpAddress(params).listen((event) {
      state.selfHelpAddressList = event["sub_unit_shop_list"];
      update();
    });
  }

  ///设置是删除还是去结算
  setDel() {
    state.edit = !state.edit;
    update();
  }

  ///批量删除
  allDed() {
    List<dynamic> list = [];
    if (state.cartData["checkedall"] != -1 &&
        state.cartDataList != null &&
        state.cartDataList.length > 0) {
      for (var i = 0; i < state.cartData["multi_shop_items"].length; i++) {
        for (var k = 0;
            k < state.cartData["multi_shop_items"][i]['cart_item_list'].length;
            k++) {
          for (var j = 0;
              j <
                  state
                      .cartData["multi_shop_items"][i]['cart_item_list'][k]
                          ['items']
                      .length;
              j++) {
            // print( state.cartData["multi_shop_items"][i]['cart_item_list'][k]['items'][j]['is_checked']);
            if (state.cartData["multi_shop_items"][i]['cart_item_list'][k]
                    ['items'][j]['is_checked'] ==
                1) {
              list.add(state.cartData["multi_shop_items"][i]['cart_item_list']
                      [k]['items'][j]['cart_id']
                  .toString());
            }
          }
        }
      }
    }

    var params = {
      "usr_num_id": state.orderMemberData["empeNumId"],
      'access_token': SpUtil.getString('token'),
      "use_platform": 2,
      "cart_id": getTaskScreen(list)
    };
    cartDelete(params);
  }

  ///或许选择的数量

  getclickNum() {
    var num = 0;
    if (state.cartData["checkedall"] != -1 &&
        state.cartDataList != null &&
        state.cartDataList.length > 0) {
      for (var i = 0; i < state.cartData["multi_shop_items"].length; i++) {
        for (var k = 0;
            k < state.cartData["multi_shop_items"][i]['cart_item_list'].length;
            k++) {
          for (var j = 0;
              j <
                  state
                      .cartData["multi_shop_items"][i]['cart_item_list'][k]
                          ['items']
                      .length;
              j++) {
            // print( state.cartData["multi_shop_items"][i]['cart_item_list'][k]['items'][j]['is_checked']);
            if (state.cartData["multi_shop_items"][i]['cart_item_list'][k]
                    ['items'][j]['is_checked'] ==
                1) {
              num = num +
                  state.cartData["multi_shop_items"][i]['cart_item_list'][k]
                          ['items'][j]['quantity']
                      .toInt();
            }
          }
        }
      }
    }

    state.clickNum = num;
    update();
  }

  ///结算
  GoSettlement() {
    if (state.cartData["checkedall"] != -1 &&
        state.cartDataList != null &&
        state.cartDataList.length > 0) {
      Get.toNamed(RouteConfig.settleAccounts, arguments: {
        'type': state.sendType,
        'orderMemberData': state.orderMemberData
      }).then((value) {
        onReady();
        update();
      });
      // }
    } else {
      toast("请先选择商品");
      return;
    }
  }

  ///数组转字符串
  String getTaskScreen(List list) {
    List tempList = [];
    String str = '';
    list.forEach((f) {
      tempList.add(f);
    });

    tempList.forEach((f) {
      if (str == '') {
        str = "$f";
      } else {
        str = "$str" "," "$f";
      }
    });

    return str;
  }

  getrecommendGoods() {
    var params = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      "use_platform": 2,

      "is_recommend": 1, //死值,推荐商品
      // "shop_id": SpUtil.getInt('storeShopNum'),
      "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      "page_no": 1,
      "page_size": 10,
      "order_by": "sold_quantity desc"
    };
    state.TJlist = [];
    update();
    Api.recommendGoods(params).listen((event) {
      if (event["code"] == 0) {
        if (event['lists'] != null && event['lists'].length > 0) {
          state.TJlist = event['lists'];
        }
        update();
      }
    });
  }

  getMoney(data) {
    String priceStr = '', oldPriceStr = '', tiShi = '';
    bool oldBool = false;
    if (data['is_seckill'] == 1) {
      // 秒杀商品
      priceStr = data['price'].toString();
      oldBool = data['mkt_price'] > data['price']; // 显示旧价格
      oldPriceStr = data['mkt_price'].toString();
    } else if (data['is_pre_sale'] == 1) {
      priceStr = data['price'].toString();
      oldBool = data['mkt_price'] > data['price']; // 显示旧价格
      oldPriceStr = data['mkt_price'].toString();
    } else {
      if (data['expect_price'] > 0) {
        priceStr = '${data['expect_price'].toString()}';
        tiShi = '折后';
        oldBool = data['mkt_price'] > data['expect_price']; // 显示旧价格
        oldPriceStr = data['mkt_price'].toString();
      } else {
        priceStr = data['price'].toString();
        oldBool = data['mkt_price'] > data['price']; // 显示旧价格
        oldPriceStr = data['mkt_price'].toString();
      }
    }
    return [priceStr, oldPriceStr];
  }

  // 添加购物车
  void bottomaddShoppingCart({
    String ec_shop_num_id,
    String item_num_id,
    String style_num_id,
    String ec_style_num_id,
  }) {
    var params = {
      "use_platform": 2, //平台
      "usr_num_id": SpUtil.getInt('empeNumId'), //会员ID
      "emp_num_id": 0, //操作员ID,移动端无属性,默认传0
      "channel_num_id": 99, //订单渠道：小程序 98，App 99
      "quantity": 1.0, //数量
      "ec_shop_num_id": ec_shop_num_id, //店铺编码
      "item_num_id": item_num_id, //商品编码
      "style_num_id": style_num_id, //款式编码
      "ec_style_num_id": ec_style_num_id, //款式唯一编码
      'access_token': SpUtil.getString('token'),
    };
    Api.addShoppingCart(params).listen((event) {
      if (event['code'] == 0) {
        mainLogic.getCartNum();
        cartGoodsData();
        toast('添加成功');
      } else {
        toast(event['message']);
      }
    });
  }
}
